<?php
// +----------------------------------------------------------------------
// | QSCMS
// +----------------------------------------------------------------------
// | Copyright (c)  2025 https://www.qqss.net All rights reserved.
// +----------------------------------------------------------------------
// | Licensed QSCMS is not free software, commercial use must purchase official license from official website to avoid unnecessary legal disputes.
// +----------------------------------------------------------------------
// | Author: Contract 990504246@qq.com
// +----------------------------------------------------------------------

namespace app\common\traits;

use app\common\model\ContentTranslation;
use app\common\model\TranslationConfig;
use app\service\translation\ContentTranslationService;

/**
 * 可翻译模型Trait
 */
trait Translatable
{
    /**
     * 可翻译的字段
     */
    protected $translatable = [];

    /**
     * 当前语言
     */
    protected $currentLanguage = 'zh_CN';

    /**
     * 模型保存后自动创建翻译任务
     */
    public static function onAfterWrite($model)
    {
        if (method_exists($model, 'createTranslationJobs')) {
            $model->createTranslationJobs();
        }
    }

    /**
     * 创建翻译任务
     */
    public function createTranslationJobs()
    {
        $tableName = $this->getTable();
        $recordId  = $this->getPk();

        $translationService = new ContentTranslationService();

        foreach ($this->getTranslatableFields() as $field) {
            // 检查字段是否有变化
            if ($this->isFieldChanged($field)) {
                $translationService->createTranslationJob($tableName, $recordId, $field);
            }
        }
    }

    /**
     * 获取可翻译字段
     */
    public function getTranslatableFields()
    {
        if (!empty($this->translatable)) {
            return $this->translatable;
        }

        // 从配置中获取
        return TranslationConfig::getTranslatableFields($this->getTable());
    }

    /**
     * 检查字段是否有变化
     */
    private function isFieldChanged($field)
    {
        return isset($this->data[$field]) &&
            $this->data[$field] !== $this->origin[$field];
    }

    /**
     * 获取翻译内容
     */
    public function getTranslation($field, $languageCode = null)
    {
        if (!$languageCode) {
            $languageCode = $this->currentLanguage;
        }

        $translationService = new ContentTranslationService();
        return $translationService->getTranslatedContent(
            $this->getTable(),
            $this->getPk(),
            $field,
            $languageCode
        );
    }

    /**
     * 获取所有翻译
     */
    public function getAllTranslations($languageCode = null)
    {
        if (!$languageCode) {
            $languageCode = $this->currentLanguage;
        }

        $translations = [];
        foreach ($this->getTranslatableFields() as $field) {
            $translations[$field] = $this->getTranslation($field, $languageCode);
        }

        return $translations;
    }

    /**
     * 设置当前语言
     */
    public function setLanguage($languageCode)
    {
        $this->currentLanguage = $languageCode;
        return $this;
    }

    /**
     * 获取当前语言
     */
    public function getLanguage()
    {
        return $this->currentLanguage;
    }

    /**
     * 获取多语言数据
     */
    public function toMultiLanguageArray($languageCode = null)
    {
        $data = $this->toArray();

        if (!$languageCode) {
            $languageCode = $this->currentLanguage;
        }

        // 如果是默认语言，直接返回
        if ($languageCode === 'zh_CN') {
            return $data;
        }

        // 替换可翻译字段的内容
        foreach ($this->getTranslatableFields() as $field) {
            $translation = $this->getTranslation($field, $languageCode);
            if ($translation) {
                $data[$field] = $translation;
            }
        }

        return $data;
    }

    /**
     * 批量获取多语言数据
     */
    public static function getMultiLanguageList($where = [], $languageCode = 'zh_CN', $field = '*', $limit = null)
    {
        $query = self::where($where);

        if ($limit) {
            $query->limit($limit);
        }

        $items = $query->field($field)->select()->toArray();

        if ($languageCode === 'zh_CN' || empty($items)) {
            return $items;
        }

        // 添加表名和记录ID信息用于批量翻译
        foreach ($items as &$item) {
            $item['_table_name'] = (new static())->getTable();
            $item['_record_id']  = $item['id'];
        }

        $translationService = new ContentTranslationService();
        return $translationService->batchGetTranslatedContent($items, $languageCode);
    }

    /**
     * 强制重新翻译
     */
    public function retranslate($field = null, $targetLanguages = null)
    {
        $tableName = $this->getTable();
        $recordId  = $this->getPk();

        $translationService = new ContentTranslationService();

        if ($field) {
            // 重新翻译指定字段
            return $translationService->createTranslationJob($tableName, $recordId, $field, $targetLanguages);
        } else {
            // 重新翻译所有字段
            $jobs = [];
            foreach ($this->getTranslatableFields() as $fieldName) {
                $jobs[] = $translationService->createTranslationJob($tableName, $recordId, $fieldName, $targetLanguages);
            }
            return $jobs;
        }
    }

    /**
     * 获取翻译状态
     */
    public function getTranslationStatus($languageCode = null)
    {
        $tableName = $this->getTable();
        $recordId  = $this->getPk();

        $status = [];
        foreach ($this->getTranslatableFields() as $field) {
            if ($languageCode) {
                $translation                   = ContentTranslation::getTranslation($tableName, $recordId, $field, $languageCode);
                $status[$field][$languageCode] = $translation ? $translation->translation_status : 0;
            } else {
                // 获取所有语言的翻译状态
                $translations = ContentTranslation::where([
                    'table_name' => $tableName,
                    'record_id'  => $recordId,
                    'field_name' => $field
                ])->select();

                foreach ($translations as $translation) {
                    $status[$field][$translation->language_code] = $translation->translation_status;
                }
            }
        }

        return $status;
    }

    /**
     * 检查是否有翻译
     */
    public function hasTranslation($field, $languageCode)
    {
        $translation = ContentTranslation::getTranslation(
            $this->getTable(),
            $this->getPk(),
            $field,
            $languageCode
        );

        return $translation && $translation->translation_status === 1;
    }

    /**
     * 获取翻译完成度
     */
    public function getTranslationCompleteness()
    {
        $tableName = $this->getTable();
        $recordId  = $this->getPk();
        $fields    = $this->getTranslatableFields();

        if (empty($fields)) {
            return 100;
        }

        $totalTranslations = ContentTranslation::where([
            'table_name'         => $tableName,
            'record_id'          => $recordId,
            'translation_status' => 1
        ])->whereIn('field_name', $fields)->count();

        $expectedTranslations = count($fields) * (count(\app\common\model\Language::getEnabledLanguages()) - 1); // 减去默认语言

        return $expectedTranslations > 0 ? round($totalTranslations / $expectedTranslations * 100, 2) : 100;
    }
}
